package com.example.bbs.controller;

import com.example.bbs.mapper.MessageMapper;
import com.example.bbs.pojo.Message;
import com.example.bbs.pojo.PageBean;
import com.example.bbs.pojo.Result;
import com.example.bbs.service.MessageService;
import com.example.bbs.utils.ThreadLocalUtil;
import com.hmall.api.client.DemoService;
import com.hmall.api.dto.User;
import io.seata.spring.annotation.GlobalTransactional;
import io.swagger.annotations.Api;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/message")
public class MessageController {
    private final RabbitTemplate rabbitTemplate;
    @Autowired
    private DemoService demoService;
    @Autowired
    public MessageMapper messageMapper;

    @Autowired
    public MessageService messageService;

    public MessageController(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    //添加留言
    @PostMapping("/addMessage")
    //通信事务 seata测试
//    @Transactional
    @GlobalTransactional
    public Result addMessage(@RequestBody Message message){
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        message.setUsername(username);
        messageMapper.addMessage(message);
        //服务通信

        String a  =new Date().toString();
        demoService.save(new User(a,"1233",""));
        System.out.println(1/0);
        return Result.success();
    }

    //分页查询留言
    @GetMapping
    public Result<PageBean<Message>> list(
            Integer pageNum,
            Integer pageSize,
            @RequestParam(required = false) String topic
    ) {
        //测试rabiit回调函数
// 1.创建CorrelationData
        CorrelationData cd = new CorrelationData();
        // 2.给Future添加ConfirmCallback
        cd.getFuture().addCallback(new ListenableFutureCallback<CorrelationData.Confirm>() {
            @Override
            public void onFailure(Throwable ex) {
                // 2.1.Future发生异常时的处理逻辑，基本不会触发
                log.error("send message fail", ex);
            }
            @Override
            public void onSuccess(CorrelationData.Confirm result) {
                // 2.2.Future接收到回执的处理逻辑，参数中的result就是回执内容
                if(result.isAck()){ // result.isAck()，boolean类型，true代表ack回执，false 代表 nack回执
                    log.debug("发送消息成功，收到 ack!");
                    System.out.println("回调成功");
                }else{ // result.getReason()，String类型，返回nack时的异常描述
                    log.error("发送消息失败，收到 nack, reason : {}", result.getReason());
                    System.out.println("message回调失败"+result.getReason());
                }
            }
        });

        try {
            rabbitTemplate.convertAndSend("test.topic", "test.success", "msg",cd);
            System.out.println("fasong");
        } catch (Exception e) {
            log.error("支付成功的消息发送失败，支付单id：{}， 交易单id：{}", e);
        }
        PageBean<Message> pb =  messageService.list(pageNum,pageSize,topic);
        return Result.success(pb);
    }

    //根据留言id查询留言
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        System.out.println(id);
        return Result.success(messageService.getById(id));
    }

    //删除留言
    @PostMapping("/delete")
    public Result deleteMessage(Integer messageId){
//        System.out.println(messageId);
        messageMapper.deleteMessage(messageId);
        return Result.success();
    }


//    //查询所有留言
//    @GetMapping("/messages")
//    public Result getMessages(){
//        System.out.println(messageMapper.getMessages());
//        return Result.success(messageMapper.getMessages());
//    }


}
